package team.scau.laboratory_repair.web.mobile.repair.web;

import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import team.scau.laboratory_repair.common.activiti.dto.RepairProcDto;
import team.scau.laboratory_repair.common.base.BaseController;
import team.scau.laboratory_repair.common.json.PoToDto;
import team.scau.laboratory_repair.common.json.Result;
import team.scau.laboratory_repair.common.json.StatusCode;
import team.scau.laboratory_repair.common.utils.ImageTool;
import team.scau.laboratory_repair.common.utils.StringTool;
import team.scau.laboratory_repair.modules.dto.DomainDto;
import team.scau.laboratory_repair.modules.dto.RepairClassifyDto;
import team.scau.laboratory_repair.modules.po.*;
import team.scau.laboratory_repair.service.*;

import java.util.*;


/**
 * @Description:
 * @Author:ZTF
 * @Date:2018/5/22 17:06
 */
@RequestMapping("/mobile/repair")
@RestController
@CommonsLog
public class RepairController extends BaseController {

    @Autowired
    private RepairService repairService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private RepairClassifyService repairClassifyService;

    @Autowired
    private UserService userService;

    @Autowired
    private NoteService noteService;

    @Autowired
    private RecordService recordService;

    @Autowired
    private DomainService domainService;

    @Autowired
    private RecordPhotoService recordPhotoService;

    @Autowired
    private PoToDto poToDto;

    @PostMapping("/submit")
    @ResponseBody
    public Result submit(Record record, @RequestParam(name = "urls", required = false) String urls) {
        Result result = new Result();
        try {
            repairService.submit(record, urls.split(","));
            result.setStatusCode(StatusCode.NO);
            result.setSuccessMsg("申请成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
            result.setSuccessMsg("申请失败");
        }
        return result;
    }

    @PostMapping("/submitphoto")
    public Result submitPhoto(@RequestParam(value = "imageList[]")String[] imageList) {
        Result result = new Result();
        List<String> imageNames = new ArrayList<>();
        try {
            String suffix = "";
            for(String str : imageList){
                //data:image/jpeg;base64，截取中间的后缀名
                suffix = "." + str.substring(11, str.lastIndexOf(";"));
                str = str.substring(str.lastIndexOf("@") + 1);
                //生成唯一uuid做图片名称
                String tmpName = "upload/record/image/" + UUID.randomUUID().toString() + suffix;
                ImageTool.GenerateImage(str, tmpName);
                imageNames.add(tmpName);
            }
            result.setStatusCode(StatusCode.NO);
            result.setData(imageNames);
            result.setSuccessMsg("上传成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
            result.setSuccessMsg("上传失败");
        }
        return result;
    }

    @PostMapping("/claim")
    public Result claim(String taskId, Long recordId, Long staffId, @RequestParam(value = "self", defaultValue = "true") Boolean self) {
        Result result = new Result();
        try {
            repairService.claim(taskId, recordId, staffId, self);
            result.setStatusCode(StatusCode.NO);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
        }
        return result;
    }

    @PostMapping("/unclaim")
    public Result unclaim(String taskId, Long recordId, @RequestParam(value = "self", defaultValue = "true") Boolean self) {
        Result result = new Result();
        try {
            repairService.unclaim(taskId, recordId, self);
            result.setStatusCode(StatusCode.NO);
            if (self) {
                result.setSuccessMsg("撤手成功");
            }else {
                result.setSuccessMsg("调离成功");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
            if (self) {
                result.setSuccessMsg("撤手失败");
            }else {
                result.setSuccessMsg("调离失败");
            }
        }
        return result;
    }

    @PostMapping("/progress")
    public Result progress(String taskId, Long recordId, String remark, @RequestParam(value = "urls[]",required = false)String[] urls) {
        Result result = new Result();
        try {
            Note note = Note.builder().recordId(recordId).staff(getCUser().getUsername()).remark(remark).build();
            repairService.note(taskId, recordId, note, urls);
            result.setStatusCode(StatusCode.NO);
            result.setSuccessMsg("记录成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
            result.setSuccessMsg("记录失败");
        }
        return result;
    }

    @PostMapping("/complete")
    public Result complete(String taskId, Long recordId, String remark, @RequestParam(defaultValue = "true")  Boolean success
            ,  @RequestParam(value = "urls[]",required = false)String[] urls) {
        Result result = new Result();
        try {
            Note note = Note.builder().recordId(recordId).staff(getCUser().getUsername()).remark(remark).build();
            repairService.complete(taskId, recordId, note, success, urls);
            result.setStatusCode(StatusCode.NO);
            result.setSuccessMsg("记录成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
            result.setSuccessMsg("记录失败");
        }
        return result;
    }

    @PostMapping("/candidate")
    public Result selectCandidateTask() {
        Result result = new Result();
        try {
            List<RepairProcDto> taskList = repairService.selectCandidateTask(getCUser().getId());
            result.setStatusCode(StatusCode.NO);
            result.setData(taskList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
        }
        return result;
    }

    @PostMapping("/history")
    public Result selectPersonalHistory(
            @RequestParam(name = "after", required = false)Date after
            , @RequestParam(name = "before", required = false)Date before
            , @RequestParam(name = "type", defaultValue = "notEnd")String type) {
        Result result = new Result();
        try {
            User cUser = getCUser();
            String openid = getOpenId();
            Boolean finished = "notEnd".endsWith(type)? Boolean.FALSE : "end".equals(type) ? Boolean.TRUE : null;
            List<RepairProcDto> procList = repairService.listHistory(cUser, openid, after, before, finished);
            result.setStatusCode(StatusCode.NO);
            result.setData(procList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
        }
        return result;
    }

    @GetMapping("/record/{id}")
    public Result getRecord(@PathVariable("id") Long id) {
        Result result = new Result();
        try {
            Record record = recordService.findById(id);
            result.setStatusCode(StatusCode.NO);
            result.setData(record);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
        }
        return result;
    }

    @GetMapping("/note/{ids}")
    public Result getNote(@PathVariable("ids") String ids) {
        Result result = new Result();
        try {
            List<Note> notes = noteService.listByIds(StringTool.strings2LongList(ids));
            result.setStatusCode(StatusCode.NO);
            result.setData(notes);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
        }
        return result;
    }

    @GetMapping("/area/{id}")
    public Result getRoomsAndClassifies(@PathVariable("id") Long areaId) {
        Result result = new Result();
        try {
            HashMap<String, Object> map = new HashMap<>();
            List<Domain> domains = domainService.listOrByExample(Domain.builder().areaId(areaId).build(), null).getResults();
            List<DomainDto> domainDtos = poToDto.domainDtoList(domains);
            map.put("rooms", domainDtos);
            List<RepairClassify> repairClassifies = repairClassifyService.listOrByExample(
                    RepairClassify.builder().locationId(areaId).build(), null).getResults();
            List<RepairClassifyDto> repairClassifyDtos = poToDto.repairClassifyList(repairClassifies);
            map.put("classifies", repairClassifyDtos);
            result.setStatusCode(StatusCode.NO);
            result.setData(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
        }
        return result;
    }

    @GetMapping("/recordphoto/{id}")
    public Result getRecordPhotos(@PathVariable("id") Long recordId) {
        Result result = new Result();
        try {
            List<RecordPhoto> photos = recordPhotoService.listByRecordId(recordId);
            result.setStatusCode(StatusCode.NO);
            result.setData(photos);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
        }
        return result;
    }

    @GetMapping("/notePhoto/{id}")
    public Result getNotePhotos(@PathVariable("id") Long noteId) {
        Result result = new Result();
        try {
            List<RecordPhoto> photos = recordPhotoService.listByNoteId(noteId);
            result.setStatusCode(StatusCode.NO);
            result.setData(photos);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
        }
        return result;
    }

    @GetMapping("/staff/{area}")
    public Result getStaffs(@PathVariable("area") Long areaId) {
        Result result = new Result();
        try {
            Area area = areaService.findById(areaId);
            List<Long> ids = StringTool.strings2LongList(area.getStaffs());
            List<User> users = userService.listByIds(ids);
            result.setStatusCode(StatusCode.NO);
            result.setData(users);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setSuccess(false);
            result.setStatusCode(StatusCode.FATAL_ERROR);
        }
        return result;
    }

}
